using Basket.Api.Data;
using Basket.Api.Domain;
using BuildingBlocks.Application.Authentication;
using BuildingBlocks.Application.Messaging;
using BuildingBlocks.Domain;
using Microsoft.EntityFrameworkCore;

namespace Basket.Api.Features.Baskets.Delete;

internal sealed class DeleteBasketCommandHandler(BasketDbContext dbContext,
    ICurrentUser currentUser)
    : ICommandHandler<DeleteBasketCommand>
{
    public async ValueTask<Result> Handle(DeleteBasketCommand request, CancellationToken cancellationToken)
    {
        Guid userId = currentUser.UserId;

        var basket = await dbContext.Baskets
            .Include(b => b.Items)
            .FirstOrDefaultAsync(b => b.UserId == userId, cancellationToken);

        if (basket is null)
        {
            return Result.Failure(BasketErrors.NotFound(currentUser.UserId));
        }

        dbContext.Baskets.Remove(basket);
        await dbContext.SaveChangesAsync(cancellationToken);

        return Result.Success();
    }
}
